import json
import os
import sys
from datetime import datetime, timedelta

import requests


class JenkinsToCloudtest:
    def __init__(self, file_path):
        self.file_path = file_path
        self.result = None
        self.start_time = 0
        self.end_time = 0
        self.test_name = ''
        self.all_num = 0
        self.pass_num = 0
        self.fail_num = 0
        self.block_num = 0
        self.result_list = list()

    def get_test_info(self):
        with open(self.file_path, 'r', encoding='utf-8',
                  errors='ignore') as f:
            for orgin_line in f.readlines():
                line = orgin_line.split()
                if 4 < len(line) <= 10:
                    self.all_num += 1
                    self.test_name = line[6].strip()
                    orgin_start_time = line[1] + ' ' + line[2]
                    self.start_time = datetime.strptime(
                        orgin_start_time.strip('[').strip(']'),
                        '%Y-%m-%d %H:%M:%S')
                    orgin_rum_time = line[3] + line[4]
                    run_time = float(orgin_rum_time.strip('[').strip(']')[
                                     :-1])
                    if 's' in orgin_rum_time:
                        self.end_time = self.start_time + timedelta(
                            seconds=run_time)
                    elif 'm' in orgin_rum_time:
                        self.end_time = self.start_time + timedelta(
                            minutes=run_time)
                    elif 'h' in orgin_rum_time:
                        self.end_time = self.start_time + timedelta(
                            hours=run_time)
                    elif 'd' in orgin_rum_time:
                        self.end_time = self.start_time + timedelta(
                            days=run_time)

                    if ': er' in orgin_line:
                        self.result = 1
                        self.fail_num += 1
                    elif ': ok' in orgin_line:
                        self.result = 0
                        self.pass_num += 1
                    elif ': to' in orgin_line:
                        self.result = 4
                        self.block_num += 1

                    test_info = {"number": self.test_name,
                                 "EndTime": self.end_time.strftime(
                                     '%Y-%m-%d %H:%M:%S'),
                                 "BeginTime": self.start_time.strftime(
                                     '%Y-%m-%d %H:%M:%S'),
                                 "caseLogUri": "no log",
                                 "failureCause": "failed reason",
                                 "Result": self.result}
                    self.result_list.append(test_info)


if __name__ == '__main__':
    Usage = "Usage:input as " \
            "'python test_http.py cloudtest_url block_id task_id src_file' "
    if len(sys.argv) < 5:
        print(Usage)
        exit(0)

    cloudtest_url = sys.argv[1]
    block_id = sys.argv[2]
    task_id = sys.argv[3]
    src_file = sys.argv[4]

    all_num = 0
    pass_num = 0
    fail_num = 0
    block_num = 0
    testcase_info_list = list()

    # 遍历所有yat_log文件，并汇总相关信息
    for file_name in os.listdir(src_file):
        if 'yat_' in file_name:
            yat_log_path = os.path.join(src_file, file_name)
            data = JenkinsToCloudtest(yat_log_path)
            data.get_test_info()
            all_num += data.all_num
            pass_num += data.pass_num
            fail_num += data.fail_num
            block_num += data.block_num
            testcase_info_list.extend(data.result_list)

    # 组合post请求data部分
    payload = {"param": {
        "testcaseBlockId": block_id,
        "testcasePass": pass_num,
        "testcaseFail": fail_num,
        "testcaseBlocked": block_num,
        "testcaseInvestigate": 1,
        "testcaseUnavailable": 1,
        "testcaseAll": all_num,
        "groupId": cloudtest_url.split('/')[2],
        "taskId": task_id,
        "result": "complete",
        "results": testcase_info_list
    }}

    headers = {'Content-Type': 'application/json'}
    payload = json.dumps(payload)
    response = requests.request("POST", cloudtest_url, headers=headers,
                                data=payload)
    print(response.text.encode('utf8'))
